package com.itheima.web.controller.store.product;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.store.Product;
import com.itheima.web.controller.BaseServlet;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(value = "/store/product")
public class ProductServlet extends BaseServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String op = request.getParameter("operation");


        if("list".equals(op)){
            list(request,response);
        }else if("show".equals(op)){
            show(request,response);
        }else if("delete".equals(op)){
            delete(request,response);
        }
    }

    //    删除功能
    private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String ids = request.getParameter("ids");
        productService.deleteProduct(ids);

        request.getRequestDispatcher("/WEB-INF/pages/store/product/product-list.jsp").forward(request,response);

    }

    //    查看商品的详情
    private void show(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String id = request.getParameter("id");

        Product product = productService.findById(id);

        request.setAttribute("product",product);

        request.getRequestDispatcher("/WEB-INF/pages/store/product/product-show.jsp").forward(request,response);

    }

    private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        int currentPage = 1;
        int pageSize = 3;

        if(StringUtils.isNotBlank(request.getParameter("currentPage"))){
            currentPage = Integer.parseInt(request.getParameter("currentPage"));
        }
        if(StringUtils.isNotBlank(request.getParameter("pageSize"))){
            pageSize =  Integer.parseInt(request.getParameter("pageSize"));
        }

        PageInfo pageInfo = productService.findByPage(currentPage, pageSize);
        request.setAttribute("page",pageInfo);
        System.out.println(pageInfo);

        request.getRequestDispatcher("/WEB-INF/pages/store/product/product-list.jsp").forward(request,response);

    }
}
